package com.hgd.security.evp.swagger.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.fasterxml.classmate.ResolvedType;
import com.google.common.base.Optional;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.Multimap;
import com.hgd.security.evp.swagger.interceptor.SwaggerInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.Lifecycle;
import org.springframework.context.SmartLifecycle;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.schema.ModelReference;
import springfox.documentation.service.*;
import springfox.documentation.spring.web.DocumentationCache;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * @author By 尚
 * @date 2019/3/28 23:47
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter implements SmartLifecycle {

    @Autowired
    private SwaggerInterceptor swaggerInterceptor;

    @Autowired
    private DocumentationCache documentationCache;

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new Hgd11FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();

        fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteNullListAsEmpty,//List字段如果为null,输出为[],而非null
            SerializerFeature.WriteNullStringAsEmpty,//字符类型字段如果为null,输出为"",而非null
            SerializerFeature.DisableCircularReferenceDetect, //消除对同一对象循环引用的问题，默认为false（如果不配置有可能会进入死循环）
            SerializerFeature.WriteMapNullValue,//是否输出值为null的字段,默认为false。
            SerializerFeature.WriteDateUseDateFormat// 定义输出日期格式
        );

        // 处理中文乱码
        List<MediaType> fastMediaTypes = new ArrayList<MediaType>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
        fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);

        converters.add(fastJsonHttpMessageConverter);

        super.configureMessageConverters(converters);
    }

    @Override
    public void start() {

        Documentation aDefault = documentationCache.documentationByGroup("default");

        Multimap<String, ApiListing> apiListings = aDefault.getApiListings();
        Collection<ApiListing> apiListings1 = apiListings.get("test-controller");
        for (ApiListing apiListing : apiListings1) {
            List<ApiDescription> apis = apiListing.getApis();
            for (ApiDescription api : apis) {
                List<Operation> operations = api.getOperations();
                for (Operation operation : operations) {
                    List<Parameter> parameters = operation.getParameters();
                    /*
                    String name,
      String description,
      String defaultValue,
      boolean required,
      boolean allowMultiple,
      Boolean allowEmptyValue,
      ModelReference modelRef,
      Optional<ResolvedType> type,
      AllowableValues allowableValues,
      String paramType,
      String paramAccess,
      boolean hidden,
      String pattern,
      String collectionFormat,
      int order,
      Object scalarExample,
      Multimap<String, Example> examples,
      List<VendorExtension> vendorExtensions
                     */
                    ModelReference modelRef=new ModelRef("java.util.Map");

                    Optional<ResolvedType> type = Optional.absent();
                    Parameter newParameter=new Parameter(
                        "newName",
                        "newDescription",
                        null,
                        true,
                        false,
                        null,
                        modelRef,
                        type,
                        null,
                        "body",
                        null,
                        false,
                        null,
                        null,
                        2147483647,
                        null,
                        LinkedListMultimap.create(),
                        new ArrayList<>()
                    );

                    parameters.add(newParameter);
                    Set<ResponseMessage> responseMessages = operation.getResponseMessages();
                    ModelReference responseModel = operation.getResponseModel();

                }
            }
        }
    }

    @Override
    public void stop() {

    }

    @Override
    public boolean isRunning() {
        return false;
    }

    @Override
    public boolean isAutoStartup() {
        return false;
    }

    @Override
    public void stop(Runnable callback) {

    }

    @Override
    public int getPhase() {
        return 0;
    }

    //    @Override
    //    public void addInterceptors(InterceptorRegistry registry) {
    //        registry.addInterceptor(swaggerInterceptor);
    //        super.addInterceptors(registry);
    //    }
}
